<?php
namespace App\Models;

use App\Events\ActivateUser;
use App\Utils\SSUtil;
use App\Utils\TreeUtil;
use App\VModels\VVip;
use Exception;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;
use Session;

/**
 * 用户模型类
 */
class MUser extends BaseModel
{
    public $table = "users";    //指定表名

    public static $STATUS_NOACTIVATED = 0;  //未激活的状态
    public static $STATUS_ACTIVATED = 1;    //已激活的状态

    public static $STATUS_NORMAL = 0;           //正常会员
    public static $STATUS_STOP = 1;             //已禁用
    public static $STATUS_FREEZE = 2;           //已冻结
    public static $STATUS_STOP_FREEZE = 3;      //已禁用+冻结

    public static $BDZX_NO = 0;       //非报单中心
    public static $BDZX_YES = 1;      //报单中心标识
    public static $BDZX_APPLY = 2;      //报单中心申请中

    public static $USER_NOIN = 0;    //非内部会员标识
    public static $USER_IN = 1;      //内部会员标识

    public static $ADDR_NO = 0;  //没有位置
    public static $ADDR_A = 1;  //A区节点
    public static $ADDR_B = 2;  //B区节点

    public static $FIRST_OK = 1;    //已经修改 过资料
    public static $FIRST_NO = 0;    //未修改过个人资料

//    public static $VIP_0 = 0;    //普通会员
//    public static $VIP_1 = 1;    //会员等级
//    public static $VIP_2 = 2;    //会员等级
//    public static $VIP_3 = 3;    //会员等级
//    public static $VIP_4 = 4;    //会员等级

    public static $VIP_0 = 'vip_0';    //普通会员等级标识
    public static $VIP_1 = 'vip_1';    //铜卡会员等级标识
    public static $VIP_2 = 'vip_2';    //银卡会员等级标识
    public static $VIP_3 = 'vip_3';    //金卡会员等级标识

    public static $ATTR_ACTIVE = 'active';  //激活会员等级属性
    public static $ATTR_POINT = 'point';    //会员等级权重属性
    public static $ATTR_UPVIP = 'upVip_award';   //会员覆盖升级属性

    public static $VIP_4 = 4;    //会员等级
    //表关系区===========================================================================

    /**
     * A节点会员 1:1
     */
    public function auser()
    {
        $auser = MUser::where('nid', $this->id)->where('addr', self::$ADDR_A)->first();

        return $auser;
    }

    /**
     * B节点会员 1:1
     */
    public function buser()
    {
        $auser = MUser::where('nid', $this->id)->where('addr', self::$ADDR_B)->first();

        return $auser;
    }

    /**
     * 会员钱包对象 1:1
     */
    public function wallet()
    {
        return $this->hasOne(MWallet::class, "uid", "id");
    }


    /**
     * 会员业绩对象 1:1
     */
    public function score()
    {
        return $this->hasOne(MScore::class, "uid", "id");
    }

    /**
     * 报单中心对象 1:1
     */
    public function bdzxUser()
    {
        return $this->hasOne(MUser::class, 'id', 'bdzx');
    }

    /**
     * 推荐人对象 1:1
     */
    public function puser()
    {
        return $this->hasOne(MUser::class, 'id', 'pid');
    }

    /**
     * 节点人对象 1:1
     */
    public function nuser()
    {
        return $this->hasOne(MUser::class, 'id', 'nid');
    }

    /**
     * 报单中心状态
     */
//    public function ubdzx()
//    {
//        return $this->hasOne(MBdzxLog::class,'uid','id');
//    }
    //数据逻辑区===========================================================================

    /**
     * 系统初始化时，添加根节点会员
     */
    public static function initalUser($username, $userpass)
    {
        $user = new MUser();
        $user->no = onlyNo();
        $user->username = $username;
        $user->userpass = $userpass;
        $user->safepass = $userpass;
        $user->reg_time = time();
        $user->ok_time = time();
        $user->ok_status = self::$STATUS_ACTIVATED;
        $user->bdzx_status = self::$BDZX_YES;
        $user->pid = 0;
        $user->nid = 0;
        $user->bdzx = 0;
        $user->ptree = 0;
        $user->ntree = 0;
        $user->in = self::$USER_IN;
        $user->vip_slug = self::$VIP_3;
        if ($user->save() && $user->addWalletScore()) {
            $wallet = $user->wallet;
            $wallet->w1 += 1000000;
            $wallet->w2 += 1000000;
            $wallet->w3 += 1000000;
            $wallet->w4 += 1000000;
            $wallet->w5 += 1000000;
            return $wallet->save();
        }
        return false;
    }

    /**
     * 随机生成一个用户对象
     */
    public static function randomUser($no)
    {
        //找到必须的节点人
        $node = TreeUtil::getNCanNode();
        $root = TreeUtil::getNTreeRoot();

        $user = new MUser();
        $user->no = onlyNo();
        $user->username = 'T' . $no;
        $user->userpass = '000000';
        $user->safepass = '000000';

        //设置会员随机等级
        $vipArr = [self::$VIP_1, self::$VIP_2, self::$VIP_3];
        $user->vip_slug = $vipArr[array_rand($vipArr, 1)];

        $user->reg_time = time();
        $user->ok_status = self::$STATUS_NOACTIVATED;   //未激活
        $user->bdzx = $root->id;

        $user->pid = $root->id;     //所有推荐人均为根节点人
        $user->plist = TreeUtil::getPListByUser($root);
        $user->ptree = $root->ptree + 1;

        $user->nid = $node->id;     //指定随机的父节点人
        $user->nlist = TreeUtil::getNListByUser($node);
        $user->ntree = $node->ntree + 1;
        $user->addr = TreeUtil::getNodeAddrByUser($node);

        if ($user->save() && $user->addWalletScore()) {
            return $user;
        }

        return null;
    }

    /**
     * 会员登录验证
     */
    public static function loginValid(Request $request)
    {
        $user = MUser::where('username', strtolower($request->username))->where('userpass', $request->userpass)->first();
        if (empty($user)) {
            return null;
        }
        return $user;
    }


    /**
     * 记录/退出会员登录状态
     *
     * $bool = true 记录登录状态， = flase  退出登录状态
     */
    public function loginStatus($bool = true)
    {
        if ($bool) {
            ss([
                'uid' => $this->id,
                'uname' => $this->username
            ]);
        } else {
            SSUtil::forget(['uid', 'uname']);
        }
        return $this;
    }

    /**
     * 记录会员登录日志
     */
    public function loginLog()
    {
        MLoginLog::log($this);
        return $this;
    }

    /**
     * 检查是否存在指定账号
     *
     * return true 存在 false 不存在
     */
    public function existUserName($username)
    {
        $user = MUser::where('username', $username)->count();
        return $user != 0;
    }

    /**
     * 注册新用户
     *
     * @param MUser $puser 推荐人
     * @param MUser $nuser 节点人
     * @param MUser $bdzx 报单中心
     * @param int $addr 节点位置
     *
     * @return boolean true = 注册成功 | false = 注册失败
     */
    public function regUser(Request $request, $puser = null, $nuser = null, $bdzx = null, $addr = null)
    {
        $this->no = onlyNo();   //生成会员编号（10位）
        $this->vip_slug = $request->vip;
        $this->userpass = $request->pass;
        $this->username = strtolower($request->name);
        $this->safepass = $request->safepass;
        $this->reg_time = time();

        //推荐人注册？
        if (!empty($puser)) {
            $this->pid = $puser->id;
            $this->bdzx = $puser->id;   //谁推荐谁激活
            $this->ptree = $puser->ptree + 1;
        }

        //节点人挂载?
        if (!empty($nuser)) {
            $this->nid = $nuser->id;
            $this->ntree = $nuser->ntree + 1;
            $this->addr = TreeUtil::getNodeAddrByUser($nuser);
            if ($this->addr == 0) { //节点人位置已满
                return false;
            }
        }

        //挂载最近节点链条
        $this->nlist = TreeUtil::getNListByUser($nuser);
        $this->plist = TreeUtil::getPListByUser($puser);
        //指定报单中心
//        if (!empty($bdzx)) {
//            $this->bdzx = $bdzx->id;
//        }

//        //会员基本信息补充？
        $this->realname = $request->realname;
        $this->email = $request->email;
        $this->mobile = $request->tel;
//        $this->receipt = $request->receipt;
        $this->first = self::$FIRST_NO; //默认新用户未修改过资料

        $result = $this->save() && $this->addWalletScore();
        return $result;
    }

    /**
     * 给用户创建资金钱包和业绩钱包
     */
    public function addWalletScore()
    {
        $wallet = new MWallet();
        $wallet->uid = $this->id;
        $score = new MScore();
        $score->uid = $this->id;
        return $wallet->save() && $score->save();
    }

    /**
     * 激活会员
     * $bdzx 会员的报单中心
     * $ok_type 会员激活方式 0 管理员/测试激活 1 方式一激活 2方式二激活
     * @param bool $bool 是否发送会员激活成功通知（结算奖金）
     * @return bool 是否激活成功
     */
    public function activation($bdzx = null, $ok_type = 0, $bool = true)
    {
        //取到报单中心
        if (empty($bdzx)) {
            $bdzx = $this->bdzxUser;
        }

        if ($puser = MUser::find($this->pid)) {
            $puser->child_num += 1;
        }

        $this->ok_status = MUser::$STATUS_ACTIVATED;
        $this->ok_time = time();

        //扣除报单币
        $bdzx_wallet = $bdzx->wallet;
//        $money = uVipBdb($this->vip);
        $money = VVip::attrBySlug($this->vip_slug)[MUser::$ATTR_ACTIVE];
        if ($ok_type == 0) {
            $this->ok_type = 0;
            if ($bool == true) {//管理员是否扣除报单币
                $bdzx_wallet->w2 -= $money;
            }
        } elseif ($ok_type == 1) {//报单币
            $this->ok_type = 1;
            $bdzx_wallet->w2 -= $money;
        } elseif ($ok_type == 2) {//报单币+奖金币
            $this->ok_type = 2;
            $bdzx_wallet->w1 -= $money * cv("bonus.jh_jjb") * 0.01;
            $bdzx_wallet->w2 -= $money * cv("bonus.jh_bdb") * 0.01;
        }

        $result = $this->save() && $bdzx_wallet->save() && $puser->save();

        if ($result && $bool) {

            //报单中心的消费记录
            if ($ok_type == 1 || $ok_type == 0) {
                MConsumeLog::log($bdzx->id, $bdzx->username, $money,
                    MConsumeLog::$CONSUME_DEDUCTING,
                    MWallet::$WALLET_TYPE_2,
                    "报单币激活会员 $this->username ($this->id), 扣除报单币".$money);
            } elseif ($ok_type == 2) {
                MConsumeLog::log($bdzx->id, $bdzx->username, $money * cv("bonus.jh_jjb") * 0.01,
                    MConsumeLog::$CONSUME_DEDUCTING,
                    MWallet::$WALLET_TYPE_1,
                    "奖金币+报单币 激活会员 $this->username ($this->id), 扣除奖金币".$money * cv("bonus.jh_jjb") * 0.01);
                MConsumeLog::log($bdzx->id, $bdzx->username, $money * cv("bonus.jh_bdb") * 0.01,
                    MConsumeLog::$CONSUME_DEDUCTING,
                    MWallet::$WALLET_TYPE_2,
                    "奖金币+报单币 激活会员 $this->username ($this->id), 扣除报单币".$money * cv("bonus.jh_bdb") * 0.01);
            }


            if ($bool) {
                event(new ActivateUser($this)); //发送会员激活成功的通知
            }

        }
        return $result;
    }

    /**
     * 开通/取消报单中心
     * $bool = true 需要扣除奖金币
     * $bool = false 不需要扣除奖金币
     * 前台会员激活方式
     */
    public function openBdzx($bool = true)
    {
        if ($this->bdzx_status == self::$BDZX_NO) {//非报单中心（提升为报单中心）
            $this->bdzx_status = self::$BDZX_YES;

        } elseif ($this->bdzx_status == self::$BDZX_YES) {//报单中心（取消报单中心身份）
            $this->bdzx_status = self::$BDZX_NO;

        }
        $wallt = $this->wallet;
        if ($bool) {
            $wallt->w1 -= cv("bonus.bdzx_money");
            MConsumeLog::log($this->id, $this->username, cv("bonus.bdzx_money"),
                MConsumeLog::$CONSUME_DEDUCTING,
                MWallet::$WALLET_TYPE_1,
                "开通报单中心身份 !");
        }

        return $this->save() && $wallt->save();
    }

    /**
     * 通过审核报单中心
     */
    public function throwBdzx()
    {
        $this->bdzx_status = self::$BDZX_YES;

        return $this->save();
    }

    /**
     * 拒绝报单中心申请
     * $bdzxlog 办单中心申请记录
     */
    public function closeBdzx($bdzxlog)
    {
        $this->bdzx_status = MUser::$BDZX_NO;
        $wallet = $this->wallet;
        if ($bdzxlog->method == 1) {

            $wallet->w1 += $bdzxlog->z_money;
            //消费记录
            MConsumeLog::log($bdzxlog->uid, $bdzxlog->username, $bdzxlog->z_money,
                MConsumeLog::$CONSUME_RECHARGE,
                MWallet::$WALLET_TYPE_1,
                "拒绝以奖金币方式申请报单中心身份 充值奖金币".$bdzxlog->z_money);
        } else if ($bdzxlog->method == 2) {
            $wallet->w1 += $bdzxlog->jjb;
            $wallet->w2 += $bdzxlog->bdb;
            //消费记录
            MConsumeLog::log($bdzxlog->uid, $bdzxlog->username, $bdzxlog->jjb,
                MConsumeLog::$CONSUME_RECHARGE,
                MWallet::$WALLET_TYPE_1,
                "拒绝以奖金币+报单币方式申请开通报单中心身份 充值奖金币".$bdzxlog->jjb);
            MConsumeLog::log($bdzxlog->uid, $bdzxlog->username, $bdzxlog->bdb,
                MConsumeLog::$CONSUME_RECHARGE,
                MWallet::$WALLET_TYPE_2,
                "拒绝以奖金币+报单币方式申请开通报单中心身份 充值报单币".$bdzxlog->bdb);
        }
        return $this->save() && $wallet->save();
    }

    /**
     * 前台申请报单中心
     */
    public function applyBdzx($method)
    {
        $this->bdzx_status = MUser::$BDZX_APPLY;
        $wallt = $this->wallet;
        if ($method == 1) {
            $wallt->w1 -= cv("bonus.bdzx_money");
            MBdzxLog::bdzxlog($this->id, $this->username, $method, cv("bonus.bdzx_money"), 0, cv("bonus.bdzx_money"));
            //消费记录
            MConsumeLog::log($this->id, $this->username, cv("bonus.bdzx_money"),
                MConsumeLog::$CONSUME_DEDUCTING,
                MWallet::$WALLET_TYPE_1,
                "奖金币申请开通报单中心身份,扣除奖金币".cv("bonus.bdzx_money"));
        }

        if ($method == 2) {
            $wallt->w1 -= getBdb(0);//奖金币
            $wallt->w2 -= getBdb(1);//报单币
            MBdzxLog::bdzxlog($this->id, $this->username, $method, getBdb(0), getBdb(1), cv("bonus.bdzx_money"));
            //消费记录
            MConsumeLog::log($this->id, $this->username, getBdb(0),
                MConsumeLog::$CONSUME_DEDUCTING,
                MWallet::$WALLET_TYPE_1,
                "奖金币+报单币 申请开通报单中心身份,扣除奖金币".getBdb(0));
            MConsumeLog::log($this->id, $this->username, getBdb(1),
                MConsumeLog::$CONSUME_DEDUCTING,
                MWallet::$WALLET_TYPE_2,
                "奖金币+报单币 申请开通报单中心身份,扣除报单币".getBdb(1));
        }
        return $wallt->save() && $this->save();
    }

    /**
     * 冻结/取消冻结用户
     */
    public static function freezeUser($id, $status)
    {
        $user = MUser::find($id);
        if ($status == MUser::$STATUS_NORMAL) {//正常状态（修改用户为冻结状态）
            $user->status = MUser::$STATUS_FREEZE;
            MLog::log("冻结了用户 $user->username ( ID: $id ) !");

        } elseif ($status == MUser::$STATUS_STOP) {//已禁用（修改用户为冻结+禁用状态）
            $user->status = MUser::$STATUS_STOP_FREEZE;
            MLog::log("冻结了用户 $user->username ( ID: $id ) !");

        } elseif ($status == MUser::$STATUS_FREEZE) {//已冻结（修改用户为正常状态）
            $user->status = MUser::$STATUS_NORMAL;
            MLog::log("取消冻结用户 $user->username ( ID: $id ) !");

        } elseif ($status == MUser::$STATUS_STOP_FREEZE) {//禁用加冻结（修改用户为禁用状态）
            $user->status = MUser::$STATUS_STOP;
            MLog::log("取消冻结用户 $user->username ( ID: $id ) !");
        }

        return $user->save();
    }

    /**
     * 禁用/取消禁用用户
     */
    public static function stopUser($id, $status)
    {
        $user = MUser::find($id);
        if ($status == MUser::$STATUS_NORMAL) {//正常状态（修改用户为禁用状态）
            $user->status = MUser::$STATUS_STOP;
            MLog::log("禁用了用户 $user->username ( ID: $id ) !");

        } elseif ($status == MUser::$STATUS_STOP) {//已禁用（修改用户为正常状态）
            $user->status = MUser::$STATUS_NORMAL;
            MLog::log("取消禁用用户 $user->username ( ID: $id ) !");

        } elseif ($status == MUser::$STATUS_FREEZE) {//已冻结（修改用户为冻结+禁用状态）
            $user->status = MUser::$STATUS_STOP_FREEZE;
            MLog::log("禁用了用户 $user->username ( ID: $id ) !");

        } elseif ($status == MUser::$STATUS_STOP_FREEZE) {//禁用加冻结（修改用户为冻结状态）
            $user->status = MUser::$STATUS_FREEZE;
            MLog::log("取消禁用用户 $user->username ( ID: $id ) !");

        }

        return $user->save();
    }

    /**
     * 编辑用户
     * return true 存储成功 false 存储失败
     */
    public function editSave(Request $request)
    {
        $this->userpass = $request->userpass;
        $this->safepass = $request->safepass;
        $this->realname = $request->realname;
        $this->mobile = $request->mobile;
        $this->receipt = $request->receipt;
        return $this->save();
    }

    /**
     * 删除当前用户
     */
    public function delUser()
    {
        //删除未激活用户，写入系统日志，删除用户钱包，删除用户业绩记录
        return $this->delete() &&
        $this->wallet->delete() &&
        $this->score->delete();
    }

    /**
     * 前台我的信息保存方法
     * return true 存储成功 false 存储失败
     */

    public function infoSave($email = "", $realname = "", $mobile = "", $receipt = "", $pic = "")
    {

        if (!empty($email)) {
            $this->email = $email;
        }

        if (!empty($realname)) {
            $this->realname = $realname;
        }

        if (!empty($mobile)) {
            $this->mobile = $mobile;
        }

        if (!empty($mobile)) {
            $this->receipt = $receipt;
        }
        if (!empty($pic)) {
            $this->pic = $pic;
        }

        $this->first = 1;
        return $this->save();
    }

    /**
     * 会员升级存入数据库
     *
     */
    public function upVip($vip)
    {
        $this->vip_slug = $vip;
        return $this->save();
    }

    /**
     * 前台个人信息管理修改登录密码
     * return true 存储成功 false 存储失败
     */
    public function modifyPass($type, $newPass)
    {
        if ($type == 1) {
            $this->userpass = $newPass;
        } elseif ($type == 2) {
            $this->safepass = $newPass;
        }
        return $this->save();
    }

    //数据验证区===========================================================================

    /**
     * 会员登录数据验证规则
     * $flag 0 = rules  1 = msg
     */
    public static function loginRulesWithMsg($flag)
    {
        $rules = array(
            "username" => "required|between:5,16",
            'userpass' => "required|between:6,18",
            'yzm' => 'required|numeric',
        );

        $msg = array(
            "username.required" => "请填写用户名",
            "username.between" => "用户名只能5-16位之间",
            "userpass.required" => "请填写登录密码",
            "userpass.between" => "登录密码只能6-18位之间",
            "yzm.required" => "请填写验证码",
            "yzm.numeric" => "验证码只能为数字",
        );

        if ($flag == 0) {
            return $rules;
        } else {
            return $msg;
        }
    }

    /**
     * 会员注册数据验证规则
     * $flag 0 = rules  1 = msg
     */
    public static function regRulesWithMsg($flag)
    {
        $rules = array(
            "name" => "required|alpha_dash|between:5,16",
            'pass' => "required|between:6,18",
            'safepass' => "required|between:6,18",
            'pname' => "required",
            'nname' => "required",
            'vip' => "required",
            'realname' => "required",
            'email' => "required|email",
            'tel' => "required",
            'sms_code' => "required",
        );

        $msg = array(
            "username.required" => "请填写用户名!",
            "username.alpha_dash" => "用户名只能为字母+数字的组合!",
            "username.between" => "用户名只能5-16位!",
            "pname.required" => "请填写推荐人!",
            "nname.required" => "请填写节点人!",
            "vip.required" => "请选择会员注册等级!",
            "pass.required" => "请填写登录密码!",
            "pass.between" => "登录密码只能6-18位!",
            "safepass.required" => "请填写交易密码!",
            "safepass.between" => "交易密码只能6-18位!",
            "realname.required" => "请填写真实姓名!",
            "email.required" => "请填写邮箱!",
            "tel.required" => "请填写手机号!",
            "sms_code.required" => "请填写短信验证码!",
        );

        if ($flag == 0) {
            return $rules;
        } else {
            return $msg;
        }
    }

    /**
     * 导出用户数据excel到服务器
     */
    public static function exportToFile()
    {
        try {
            $cellData = [];
            $cellData[] = [
                '会员ID', '会员唯一编号', '用户名', '用户密码',
                '安全密码', '用户等级', '注册时间', '激活时间',
                '激活状态', '帐号状态', '报单中心状态', '推广人', '节点人',
                '报单中心人', '推广层级深度', '节点层级深度', '相对位置', '推广的已激活子会员',
                '是否内部会员', '真实姓名', '联系方式', '收款账户', '是否已修改过会员资料',
                '奖金币可用余额', '奖金币冻结余额', '奖金币累计总收入',
                '报单币可用余额', '报单币冻结余额', '保单币累计总收入',
                '购货币可用余额', '购货币冻结余额', '购货币累计总收入',
                'A区总业绩', 'B区总业绩', 'A区结余', 'B区结余', '当天结余总金额', '上次结余时间'
            ];
            $time = time();
            //切片处理数据
            MUser::chunk(100, function ($users) use (&$cellData) {
                foreach ($users as $user) {

                    //注册时间和激活时间
                    $user->reg_time = date('Y-m-d H:i:s', $user->reg_time);
                    $user->ok_time = date('Y-m-d H:i:s', $user->ok_time);

                    //用户等级
                    if ($user->vip_slug == MUser::$VIP_0) {
                        $user->vip = VVip::vipBySlug(MUser::$VIP_0)->name;
                    } elseif ($user->vip_slug == MUser::$VIP_1) {
                        $user->vip = VVip::vipBySlug(MUser::$VIP_1)->name;
                    } elseif ($user->vip_slug == MUser::$VIP_2) {
                        $user->vip = VVip::vipBySlug(MUser::$VIP_2)->name;
                    } elseif ($user->vip_slug == MUser::$VIP_3) {
                        $user->vip = VVip::vipBySlug(MUser::$VIP_3)->name;
                    }

                    //激活状态
                    if ($user->ok_status == 0) {
                        $user->ok_status = '未激活';
                    } elseif ($user->ok_status == 1) {
                        $user->ok_status = '已激活';
                    }

                    //帐号状态
                    if ($user->status == 0) {
                        $user->status = '正常';
                    } elseif ($user->status == 1) {
                        $user->status = '已禁用';
                    } elseif ($user->status == 2) {
                        $user->status = '已冻结';
                    } elseif ($user->status == 3) {
                        $user->status = '禁用+冻结';
                    }

                    //报单中心状态
                    if ($user->bdzx_status == 0) {
                        $user->bdzx_status = '否';
                    } elseif ($user->bdzx_status == 1) {
                        $user->bdzx_status = '是';
                    } elseif ($user->bdzx_status == 2) {
                        $user->bdzx_status = '申请中';
                    }

                    //相对父节点位置
                    if ($user->addr == 1) {
                        $user->addr = 'A区';
                    } elseif ($user->addr == 2) {
                        $user->addr = 'B区';
                    } elseif ($user->addr == 3) {
                        $user->addr = 'C区';
                    }

                    //是否内部会员
                    if ($user->in == 0) {
                        $user->in = '否';
                    } elseif ($user->in == 1) {
                        $user->in = '是';
                    }

                    //是否已修改会员资料
                    if ($user->first == 0) {
                        $user->first = '未修改';
                    } elseif ($user->first == 1) {
                        $user->first = '已修改';
                    }

                    //放值
                    $cellData[] = [
                        $user->id, $user->no, $user->username, $user->userpass,
                        $user->safepass, $user->vip, $user->reg_time, $user->ok_time,
                        $user->ok_status, $user->status, $user->bdzx_status, $user->pid, $user->nid,
                        $user->bdzx, $user->ptree, $user->ntree, $user->addr, $user->child_num,
                        $user->in, $user->realname, $user->mobile, $user->receipt, $user->first,
                        $user->wallet->w1, $user->wallet->w1_freeze, $user->wallet->w1_count,
                        $user->wallet->w2, $user->wallet->w2_freeze, $user->wallet->w2_count,
                        $user->wallet->w3, $user->wallet->w3_freeze, $user->wallet->w3_count,
                        $user->wallet->a_count, $user->wallet->b_count, $user->wallet->a_over, $user->wallet->b_over, $user->wallet->day_over, date('Y-m-d H:i:s', $user->wallet->over_time)
                    ];
                }
            });

            //导出数据到文件
            Excel::create(date('Y-m-d H_i') . ' Users', function ($excel) use ($cellData) {
                $excel->sheet('score', function ($sheet) use ($cellData) {
                    $sheet->rows($cellData);
                });
            })->store('xls', public_path('exports'));

        } catch (Exception $e) {
            return false;
        }
        return true;
    }

    /**
     * 前台个人信息修改数据验证规则
     * $flag 0 = rules  1 = msg
     */
    public static function myInfoRulesWithMsg($flag)
    {

        $rules = array(
            'realname' => "required|max: 5",
            'mobile' => "required|max: 20",
//            'receipt' => "required|max: 50",
        );

        $msg = array(
            "realname.required" => "真实姓名必须填写",
            "realname.max" => "真实姓名不能超过5位字符",
            "mobile.required" => "联系方式必须填写",
            "mobile.max" => "联系方式不能超过20位字符",
//            "receipt.required" => "收款账户必须填写",
//            "receipt.max" => "收款账户不能超过50位字符",
        );

        if ($flag == 0) {
            return $rules;
        } else {
            return $msg;
        }
    }

    /**
     * 前台个人信息修改密码验证规则
     * $flag 0 = rules  1 = msg
     */
    public static function modifyPassRulesWithMsg($flag)
    {

        $rules = array(
            'type' => "required",
            'oldpass' => "required|between:5,50",
            'newpass' => "required|between:5,50",
        );

        $msg = array(
            "type" => "请选择修改密码类型",
            "oldpass.required" => "原密码必须填写",
            "oldpass.between" => "原密码位于5-50位字符之间",
            "newpass.required" => "新密码必须填写",
            "newpass.between" => "新密码位于5-50位字符之间",
        );

        if ($flag == 0) {
            return $rules;
        } else {
            return $msg;
        }
    }

    /**
     * 会员编辑数据验证规则
     * $flag 0 = rules  1 = msg
     */
    public static function editRulesWithMsg($flag)
    {

        $rules = array(
            'userpass' => "required|between:6,30",
            'safepass' => "required|between:6,30",
            'realname' => "max: 5",
            'mobile' => "max: 20",
            'receipt' => "max: 50",
        );

        $msg = array(
            "userpass.required" => "密码不能为空",
            "userpass.between" => "密码只能6-30位之间",
            "safepass.required" => "安全密码不能为空",
            "safepass.between" => "安全密码只能6-30位之间",
            "realname.max" => "真实姓名不能超过5位字符",
            "mobile.max" => "联系方式不能超过20位字符",
            "receipt.max" => "收款账户不能超过50位字符",
        );

        if ($flag == 0) {
            return $rules;
        } else {
            return $msg;
        }
    }

    /**
     * 给根节点创建资金钱包和业绩钱包
     */
    public function addRootWalletScore()
    {
        $wallet = new MWallet();
        $wallet->uid = $this->id;
        $wallet->w1 = 1000000;
        $wallet->w1_count = 1000000;
        $wallet->w2 = 1000000;
        $wallet->w2_count = 1000000;
        $wallet->w3 = 1000000;
        $wallet->w3_count = 1000000;
        $wallet->w4 = 1000000;
        $wallet->w4_count = 1000000;
        $wallet->w5 = 1000000;
        $wallet->w5_count = 1000000;
        $score = new MScore();
        $score->uid = $this->id;
        return $wallet->save() && $score->save();
    }

}